/**
 * 快手直播大屏数据弹窗模组
 * 处理直播数据记录和显示
 */
import cssText from "data-text:~/assets/css/data_screen.css"
import antdResetCssText from "data-text:antd/dist/reset.css"
import moment from "moment"
import type { PlasmoCSConfig, PlasmoGetShadowHostId } from "plasmo"
import React, { useEffect, useState } from "react"

import { usePort } from "@plasmohq/messaging/hook"

import DataRecordModalIndex from "~ui_components/DataRecordModalIndex"

// 注入配置
export const config: PlasmoCSConfig = {
  matches: [
    // 快手直播数据大屏(专业版)
    "https://zs.kwaixiaodian.com/realtime/operating/systemMain*",
    // 快手直播数据大屏(专业新版 2024/09/20)
    "https://zs.kwaixiaodian.com/realtime/operating/zones/dataScreen/main*"
  ],
  run_at: "document_end",
  all_frames: true
}

/**
 * 区别于抖音, 快手直播的数据大屏挂载到html下的shadow dom中
 * 可能因为淘宝的antd妨碍自定义挂载body下的shadow dom，导致样式失败
 */

// 注入的shadow dom的id
export const HOST_ID = "data-record-modal"
export const getShadowHostId: PlasmoGetShadowHostId = () => HOST_ID

// 注入样式
export const getStyle = () => {
  const style = document.createElement("style")
  style.textContent = cssText + antdResetCssText
  return style
}

const KsDataRecordModal: React.FC = () => {
  // 快手直播大屏数据Port
  const ksLiveScreenData = usePort("ksLiveScreenData")

  // hijackEvent事件响应方法
  const eventHandler = (
    event: CustomEvent<{
      url: string
      response: any
    }>
  ) => {
    ksLiveScreenData.send(event.detail)
  }

  useEffect(() => {
    // 数据初始化
    ksLiveScreenData.send({ action: "init" })
    // 监听ksLiveScreenData消息
    window.addEventListener("hijackEvent", eventHandler)
    // 清理监听
    return () => {
      window.removeEventListener("hijackEvent", eventHandler)
    }
  }, [])

  return (
    <DataRecordModalIndex HostId={HOST_ID} hijackData={ksLiveScreenData.data} />
  )
}

export default KsDataRecordModal
